Python OpenCV |
您所在的位置:网站首页 › cv2 imdecode › Python OpenCV |
Python cv2.imdecode() function is used to read image data from a memory cache and convert it into image format. This is generally used for loading the image efficiently from the internet. Syntax: cv2.imdecode(buf,flags) Parameters: buf – It is the image data received in bytesflags – It specifies the way in which image should be read. It鈥檚 default value is cv2.IMREAD_COLORReturn: Image array Note: If buf given is not image data then NULL will be returned. Example 1: Python3#import modulesimport numpy as npimport urllib.requestimport cv2 # read the image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # read image as an numpy array image = np.asarray(bytearray(resp.read()), dtype="uint8") # use imdecode function image = cv2.imdecode(image, cv2.IMREAD_COLOR) # display image cv2.imwrite("result.jpg", image)Output: Example 2: If grayscale is required, then 0 can be used as flag. Python3# import necessary modulesimport numpy as npimport urllib.requestimport cv2 # read image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png' with urllib.request.urlopen(url) as resp: # convert to numpy array image = np.asarray(bytearray(resp.read()), dtype="uint8") # 0 is used for grayscale image image = cv2.imdecode(image, 0) # display image cv2.imwrite("result.jpg", image)Output: Example 3: Reading image from a file Input Image: Python3# import necessayr modulesimport numpy as npimport urllib.requestimport cv2 # read th imagewith open("image.jpg", "rb") as image: f = image.read() # convert to numpy array image = np.asarray(bytearray(f)) # RGB to Grayscale image = cv2.imdecode(image, 0) # display image cv2.imshow("output", image)Output: |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |